import React, { useState } from 'react';
import { invoke } from '@tauri-apps/api/core';
import { open, save } from '@tauri-apps/plugin-dialog';
import {
  FolderIcon,
  DocumentTextIcon,
  PencilIcon,
  EyeIcon,
  ArrowDownTrayIcon,
  ArrowUpTrayIcon,
  PhotoIcon,
  FilmIcon,
  MusicalNoteIcon,
  DocumentIcon,
} from '@heroicons/react/24/outline';

interface FileItem {
  name: string;
  path: string;
  isDirectory: boolean;
  size?: number;
  modified?: string;
}

// 根据文件扩展名获取图标
const getFileIcon = (fileName: string, isDirectory: boolean) => {
  if (isDirectory) {
    return FolderIcon;
  }

  const extension = fileName.split('.').pop()?.toLowerCase() || '';

  // 图片文件
  if (
    ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'svg', 'webp', 'ico'].includes(
      extension
    )
  ) {
    return PhotoIcon;
  }

  // 视频文件
  if (['mp4', 'avi', 'mov', 'wmv', 'flv', 'webm', 'mkv'].includes(extension)) {
    return FilmIcon;
  }

  // 音频文件
  if (['mp3', 'wav', 'flac', 'aac', 'ogg', 'wma'].includes(extension)) {
    return MusicalNoteIcon;
  }

  // 文本文件
  if (
    [
      'txt',
      'md',
      'json',
      'js',
      'ts',
      'tsx',
      'jsx',
      'css',
      'html',
      'htm',
      'xml',
      'yaml',
      'yml',
      'toml',
      'ini',
      'cfg',
      'conf',
      'log',
      'csv',
      'rs',
      'py',
      'java',
      'c',
      'cpp',
      'h',
      'hpp',
      'go',
      'php',
      'rb',
      'sh',
      'bat',
      'ps1',
      'sql',
    ].includes(extension)
  ) {
    return DocumentTextIcon;
  }

  // 其他文档文件
  if (
    ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx'].includes(extension)
  ) {
    return DocumentIcon;
  }

  // 默认文件图标
  return DocumentTextIcon;
};

// 检查文件是否可以编辑
const isEditableFile = (fileName: string) => {
  const extension = fileName.split('.').pop()?.toLowerCase() || '';
  const editableExtensions = [
    'txt',
    'md',
    'json',
    'js',
    'ts',
    'tsx',
    'jsx',
    'css',
    'html',
    'htm',
    'xml',
    'yaml',
    'yml',
    'toml',
    'ini',
    'cfg',
    'conf',
    'log',
    'csv',
    'rs',
    'py',
    'java',
    'c',
    'cpp',
    'h',
    'hpp',
    'go',
    'php',
    'rb',
    'sh',
    'bat',
    'ps1',
    'sql',
    'gitignore',
    'dockerfile',
    'makefile',
  ];
  return editableExtensions.includes(extension) || extension === '';
};

const FileManager: React.FC = () => {
  const [currentPath, setCurrentPath] = useState('');
  const [files, setFiles] = useState<FileItem[]>([]);
  const [selectedFile, setSelectedFile] = useState<string | null>(null);
  const [fileContent, setFileContent] = useState('');
  const [isEditing, setIsEditing] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // 新建文件/文件夹
  const [showCreateDialog, setShowCreateDialog] = useState(false);
  const [createType, setCreateType] = useState<'file' | 'directory'>('file');
  const [createName, setCreateName] = useState('');

  // 加载目录内容
  const loadDirectory = async (path?: string) => {
    try {
      setLoading(true);
      setError(null);

      let targetPath = path;
      if (!targetPath) {
        // 如果没有指定路径，使用当前路径或获取主目录
        if (currentPath) {
          targetPath = currentPath;
        } else {
          targetPath = await invoke<string>('get_home_directory');
        }
      }

      const fileList = await invoke<FileItem[]>('read_directory', {
        path: targetPath,
      });
      setFiles(fileList);
      setCurrentPath(targetPath);
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
      setFiles([]);
    } finally {
      setLoading(false);
    }
  };

  // 导航到目录
  const navigateToDirectory = async (path: string) => {
    await loadDirectory(path);
    setSelectedFile(null);
    setFileContent('');
    setIsEditing(false);
  };

  const loadFileContent = async (filePath: string) => {
    try {
      setLoading(true);
      setError(null);

      // 首先检查是否为文本文件
      const isTextFile = await invoke<boolean>('is_text_file', {
        path: filePath,
      });

      if (!isTextFile) {
        setError(
          'This file type is not supported for text editing. Only text files can be opened.'
        );
        setSelectedFile(null);
        setFileContent('');
        return;
      }

      const content = await invoke<string>('read_text_file', {
        path: filePath,
      });
      setFileContent(content);
      setSelectedFile(filePath);
      setIsEditing(false);
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : String(err);
      setError(errorMessage);
      setSelectedFile(null);
      setFileContent('');
    } finally {
      setLoading(false);
    }
  };

  const saveFileContent = async () => {
    if (!selectedFile) return;

    try {
      setLoading(true);
      setError(null);

      await invoke<boolean>('write_text_file', {
        path: selectedFile,
        content: fileContent,
      });

      setIsEditing(false);
      alert('文件保存成功！');
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
    } finally {
      setLoading(false);
    }
  };

  const createFileOrDirectory = async () => {
    if (!createName.trim()) return;

    try {
      setLoading(true);
      setError(null);

      const separator = currentPath.includes('\\') ? '\\' : '/';
      const fullPath = currentPath
        ? `${currentPath}${separator}${createName}`
        : createName;

      if (createType === 'directory') {
        await invoke<boolean>('create_directory', { path: fullPath });
      } else {
        await invoke<boolean>('write_text_file', {
          path: fullPath,
          content: '',
        });
      }

      setShowCreateDialog(false);
      setCreateName('');
      alert(`${createType === 'directory' ? '文件夹' : '文件'}创建成功！`);

      // 重新加载当前目录
      await loadDirectory(currentPath);
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
    } finally {
      setLoading(false);
    }
  };

  // 初始化加载
  React.useEffect(() => {
    loadDirectory();
  }, []);

  const openFile = async () => {
    try {
      const selected = await open({
        multiple: false,
        filters: [
          {
            name: 'Text Files',
            extensions: [
              'txt',
              'md',
              'json',
              'js',
              'ts',
              'tsx',
              'jsx',
              'css',
              'html',
              'xml',
              'yaml',
              'yml',
            ],
          },
        ],
      });

      if (selected) {
        await loadFileContent(selected as string);
        setCurrentPath(selected as string);
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
    }
  };

  const saveAsFile = async () => {
    try {
      const filePath = await save({
        filters: [
          {
            name: 'Text Files',
            extensions: [
              'txt',
              'md',
              'json',
              'js',
              'ts',
              'tsx',
              'jsx',
              'css',
              'html',
              'xml',
              'yaml',
              'yml',
            ],
          },
        ],
      });

      if (filePath) {
        await invoke<boolean>('write_text_file', {
          path: filePath,
          content: fileContent,
        });

        setSelectedFile(filePath);
        setCurrentPath(filePath);
        alert('文件保存成功！');
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
    }
  };

  const formatFileSize = (bytes: number) => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  return (
    <div className="flex h-full">
      {/* 左侧文件浏览器 */}
      <div className="w-1/3 border-r border-gray-200 bg-white dark:border-gray-700 dark:bg-gray-800">
        <div className="border-b border-gray-200 p-4 dark:border-gray-700">
          <div className="mb-4 flex items-center justify-between">
            <h2 className="text-lg font-semibold">文件管理器</h2>
            <div className="flex space-x-2">
              <button
                onClick={openFile}
                className="rounded p-2 text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900/20"
                title="打开文件"
              >
                <ArrowUpTrayIcon className="h-4 w-4" />
              </button>
              <button
                onClick={() => {
                  setShowCreateDialog(true);
                  setCreateType('file');
                }}
                className="rounded p-2 text-green-600 hover:bg-green-50 dark:hover:bg-green-900/20"
                title="新建文件"
              >
                <DocumentTextIcon className="h-4 w-4" />
              </button>
              <button
                onClick={() => {
                  setShowCreateDialog(true);
                  setCreateType('directory');
                }}
                className="rounded p-2 text-purple-600 hover:bg-purple-50 dark:hover:bg-purple-900/20"
                title="新建文件夹"
              >
                <FolderIcon className="h-4 w-4" />
              </button>
            </div>
          </div>

          {currentPath && (
            <div className="break-all text-xs text-gray-500 dark:text-gray-400">
              当前路径: {currentPath}
            </div>
          )}
        </div>

        <div className="p-4">
          {loading ? (
            <div className="py-8 text-center text-gray-500 dark:text-gray-400">
              <div className="mx-auto mb-2 h-8 w-8 animate-spin rounded-full border-b-2 border-blue-600"></div>
              <p>加载中...</p>
            </div>
          ) : files.length === 0 ? (
            <div className="py-8 text-center text-gray-500 dark:text-gray-400">
              <FolderIcon className="mx-auto mb-2 h-12 w-12 opacity-50" />
              <p>此目录为空</p>
              <p className="mt-1 text-xs">使用上方按钮创建新文件或文件夹</p>
            </div>
          ) : (
            <div className="space-y-1">
              {/* 返回上级目录按钮 */}
              {currentPath && currentPath !== '/' && (
                <div
                  onClick={() => {
                    const parentPath = currentPath
                      .split(/[/\\]/)
                      .slice(0, -1)
                      .join(currentPath.includes('\\') ? '\\' : '/');
                    navigateToDirectory(
                      parentPath || (currentPath.includes('\\') ? 'C:\\' : '/')
                    );
                  }}
                  className="flex cursor-pointer items-center rounded border-b border-gray-200 p-2 hover:bg-gray-100 dark:border-gray-600 dark:hover:bg-gray-700"
                >
                  <FolderIcon className="mr-2 h-5 w-5 text-gray-400" />
                  <div className="text-sm font-medium text-gray-600 dark:text-gray-400">
                    .. (上级目录)
                  </div>
                </div>
              )}

              {files.map((file, index) => {
                const IconComponent = getFileIcon(file.name, file.isDirectory);
                const canEdit = !file.isDirectory && isEditableFile(file.name);

                return (
                  <div
                    key={index}
                    onClick={() => {
                      if (file.isDirectory) {
                        navigateToDirectory(file.path);
                      } else if (canEdit) {
                        loadFileContent(file.path);
                      }
                    }}
                    className={`flex items-center rounded p-2 ${
                      file.isDirectory || canEdit
                        ? 'cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-700'
                        : 'cursor-not-allowed opacity-60'
                    } ${selectedFile === file.path ? 'bg-blue-100 dark:bg-blue-900/20' : ''}`}
                  >
                    <IconComponent
                      className={`mr-2 h-5 w-5 ${
                        file.isDirectory
                          ? 'text-blue-500'
                          : canEdit
                            ? 'text-gray-500'
                            : 'text-gray-400'
                      }`}
                    />
                    <div className="min-w-0 flex-1">
                      <div
                        className={`truncate text-sm font-medium ${
                          canEdit || file.isDirectory ? '' : 'text-gray-400'
                        }`}
                      >
                        {file.name}
                        {!file.isDirectory && !canEdit && (
                          <span className="ml-1 text-xs text-gray-400">
                            (不支持编辑)
                          </span>
                        )}
                      </div>
                      <div className="flex items-center space-x-2 text-xs text-gray-500">
                        {file.size !== undefined && (
                          <span>{formatFileSize(file.size)}</span>
                        )}
                        {file.modified && (
                          <span>
                            {new Date(file.modified).toLocaleDateString()}
                          </span>
                        )}
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>

      {/* 右侧文件编辑器 */}
      <div className="flex flex-1 flex-col bg-white dark:bg-gray-800">
        <div className="border-b border-gray-200 p-4 dark:border-gray-700">
          <div className="flex items-center justify-between">
            <h2 className="text-lg font-semibold">
              {selectedFile
                ? `编辑: ${selectedFile.split('/').pop()}`
                : '文本编辑器'}
            </h2>

            {selectedFile && (
              <div className="flex space-x-2">
                <button
                  onClick={() => setIsEditing(!isEditing)}
                  className={`rounded px-3 py-1 text-sm ${
                    isEditing
                      ? 'bg-yellow-100 text-yellow-700 hover:bg-yellow-200'
                      : 'bg-blue-100 text-blue-700 hover:bg-blue-200'
                  }`}
                >
                  {isEditing ? (
                    <>
                      <EyeIcon className="mr-1 inline h-4 w-4" />
                      预览
                    </>
                  ) : (
                    <>
                      <PencilIcon className="mr-1 inline h-4 w-4" />
                      编辑
                    </>
                  )}
                </button>

                {isEditing && (
                  <button
                    onClick={saveFileContent}
                    disabled={loading}
                    className="rounded bg-green-600 px-3 py-1 text-sm text-white hover:bg-green-700 disabled:opacity-50"
                  >
                    保存
                  </button>
                )}

                <button
                  onClick={saveAsFile}
                  className="rounded bg-purple-600 px-3 py-1 text-sm text-white hover:bg-purple-700"
                >
                  <ArrowDownTrayIcon className="mr-1 inline h-4 w-4" />
                  另存为
                </button>
              </div>
            )}
          </div>

          {error && (
            <div className="mt-2 rounded border border-red-200 bg-red-100 p-2 text-sm text-red-700 dark:border-red-800 dark:bg-red-900/20 dark:text-red-400">
              {error}
            </div>
          )}
        </div>

        <div className="flex-1 p-4">
          {loading ? (
            <div className="flex h-full items-center justify-center">
              <div className="h-8 w-8 animate-spin rounded-full border-b-2 border-blue-600"></div>
              <span className="ml-2">处理中...</span>
            </div>
          ) : selectedFile ? (
            <div className="h-full">
              {isEditing ? (
                <textarea
                  value={fileContent}
                  onChange={e => setFileContent(e.target.value)}
                  className="h-full w-full resize-none rounded-lg border border-gray-300 bg-white p-4 font-mono text-sm text-gray-900 focus:outline-none focus:ring-2 focus:ring-blue-500 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-100"
                  placeholder="在此输入文件内容..."
                />
              ) : (
                <pre className="h-full w-full overflow-auto whitespace-pre-wrap rounded-lg border border-gray-300 bg-gray-50 p-4 font-mono text-sm text-gray-900 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-100">
                  {fileContent || '文件为空'}
                </pre>
              )}
            </div>
          ) : (
            <div className="flex h-full items-center justify-center text-gray-500 dark:text-gray-400">
              <div className="text-center">
                <DocumentTextIcon className="mx-auto mb-4 h-16 w-16 opacity-50" />
                <p className="mb-2 text-lg">选择一个文件开始编辑</p>
                <p className="text-sm">或者创建一个新文件</p>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* 创建文件/文件夹对话框 */}
      {showCreateDialog && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50">
          <div className="w-96 rounded-lg bg-white p-6 dark:bg-gray-800">
            <h3 className="mb-4 text-lg font-semibold">
              创建{createType === 'directory' ? '文件夹' : '文件'}
            </h3>

            <input
              type="text"
              value={createName}
              onChange={e => setCreateName(e.target.value)}
              placeholder={`输入${createType === 'directory' ? '文件夹' : '文件'}名称`}
              className="mb-4 w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-gray-900 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-100"
              onKeyDown={e => e.key === 'Enter' && createFileOrDirectory()}
            />

            <div className="flex justify-end space-x-2">
              <button
                onClick={() => {
                  setShowCreateDialog(false);
                  setCreateName('');
                }}
                className="rounded px-4 py-2 text-gray-600 hover:bg-gray-100 dark:text-gray-400 dark:hover:bg-gray-700"
              >
                取消
              </button>
              <button
                onClick={createFileOrDirectory}
                disabled={!createName.trim() || loading}
                className="rounded bg-blue-600 px-4 py-2 text-white hover:bg-blue-700 disabled:opacity-50"
              >
                创建
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default FileManager;
